package com.rj.core.validation;


import com.rj.core.exception.BaseException;
import com.rj.core.validation.constraints.DateField;
import com.rj.util.AssertBeanUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @author YFX_RANLUBO
 */
public class DateFieldValidator implements ConstraintValidator<DateField, String> {
    /**
     * 对象属性注解
     */
    private DateField checkField;
    /**
     * 是否允许为空
     */
    private boolean allowEmpty;
    /**
     * 属性名称
     */
    private String name;

    private String[] formats;

    public DateFieldValidator() {
    }

    @Override
    public void initialize(DateField checkField) {
        this.allowEmpty = checkField.empty();
        this.name = checkField.value();
        this.formats = checkField.dateFormat();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        try {
            AssertBeanUtils.check(value, name, allowEmpty).dateFormat(formats);
        } catch (BaseException e) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(e.getMessage()).addConstraintViolation();
            return false;
        }

        return true;
    }
}